<script setup>
import { ref, onMounted } from 'vue'
import { ElTable, ElTableColumn, ElButton, ElIcon, ElDialog, ElForm, ElFormItem, ElInput, ElPagination, ElMessageBox, ElNotification, ElBadge } from 'element-plus'
import { Search, Refresh, Download, Filter, Send, Bell, Trash, FileText, User, CheckCircle, Clock } from '@element-plus/icons-vue'

// 消息列表数据
const messageList = ref([])
// 搜索关键词
const searchKeyword = ref('')
// 当前页码
const currentPage = ref(1)
// 每页条数
const pageSize = ref(10)
// 总条数
const total = ref(0)
// 加载状态
const loading = ref(false)
// 查看对话框显示状态
const viewDialogVisible = ref(false)
// 当前查看的消息
const currentMessage = ref({})
// 未读消息数量
const unreadCount = ref(0)

// 加载消息列表
const loadMessageList = async () => {
  loading.value = true
  try {
    // 模拟API请求延迟
    await new Promise(resolve => setTimeout(resolve, 500))
    // 模拟数据
    const mockData = Array.from({ length: 25 }, (_, index) => ({
      id: index + 1,
      title: `消息标题${index + 1}`,
      content: `这是消息内容${index + 1}，包含了一些详细信息和通知内容。`,
      sender: ['系统通知', '管理员', '张老师', '李老师', '王老师'][Math.floor(Math.random() * 5)],
      sendTime: new Date(Date.now() - Math.floor(Math.random() * 7 * 24 * 60 * 60 * 1000)),
      isRead: Math.random() > 0.4,
      type: ['通知', '提醒', '警告', '消息'][Math.floor(Math.random() * 4)]
    }))

    // 计算未读消息数量
    unreadCount.value = mockData.filter(item => !item.isRead).length

    // 筛选数据
    let filteredData = mockData
    if (searchKeyword.value) {
      filteredData = mockData.filter(item =>
        item.title.includes(searchKeyword.value) ||
        item.content.includes(searchKeyword.value) ||
        item.sender.includes(searchKeyword.value)
      )
    }

    // 按时间倒序排序
    filteredData.sort((a, b) => b.sendTime - a.sendTime)

    // 分页
    total.value = filteredData.length
    messageList.value = filteredData.slice(
      (currentPage.value - 1) * pageSize.value,
      currentPage.value * pageSize.value
    )
  } catch (error) {
    ElNotification.error('获取消息列表失败')
    console.error('Failed to load message list:', error)
  } finally {
    loading.value = false
  }
}

// 搜索消息
const searchMessages = () => {
  currentPage.value = 1
  loadMessageList()
}

// 重置搜索
const resetSearch = () => {
  searchKeyword.value = ''
  currentPage.value = 1
  loadMessageList()
}

// 打开查看对话框
const openViewDialog = (row) => {
  currentMessage.value = { ...row }
  // 标记为已读
  if (!row.isRead) {
    row.isRead = true
    unreadCount.value--
  }
  viewDialogVisible.value = true
}

// 关闭查看对话框
const closeViewDialog = () => {
  viewDialogVisible.value = false
}

// 删除消息
const deleteMessage = async (id) => {
  try {
    const result = await ElMessageBox.confirm('确定要删除该消息吗？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    if (result === 'confirm') {
      // 模拟API请求延迟
      await new Promise(resolve => setTimeout(resolve, 500))
      // 删除数据
      const deletedItem = messageList.value.find(item => item.id === id)
      if (deletedItem && !deletedItem.isRead) {
        unreadCount.value--
      }
      messageList.value = messageList.value.filter(item => item.id !== id)
      total.value--
      ElNotification.success('删除成功')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElNotification.error('删除失败')
      console.error('Failed to delete message:', error)
    }
  }
}

// 标记所有消息为已读
const markAllAsRead = async () => {
  try {
    // 模拟API请求延迟
    await new Promise(resolve => setTimeout(resolve, 500))
    // 标记所有消息为已读
    messageList.value.forEach(item => {
      item.isRead = true
    })
    unreadCount.value = 0
    ElNotification.success('所有消息已标记为已读')
  } catch (error) {
    ElNotification.error('操作失败')
    console.error('Failed to mark all as read:', error)
  }
}

// 下载数据
const downloadData = () => {
  ElNotification.info('数据下载中...')
  // 实际应用中这里应该实现数据导出功能
}

// 分页大小变化
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  loadMessageList()
}

// 当前页变化
const handleCurrentChange = (current) => {
  currentPage.value = current
  loadMessageList()
}

// 页面加载时获取数据
onMounted(() => {
  loadMessageList()
})
</script>

<template>
  <div class="messages-container">
    <div class="header">
      <h2>消息管理</h2>
      <div class="search-bar">
        <el-input
          v-model="searchKeyword"
          placeholder="请输入标题、内容或发送者"
          prefix-icon="Search"
          style="width: 300px; margin-right: 10px;"
        />
        <el-button type="primary" @click="searchMessages">
          <el-icon><Search /></el-icon> 搜索
        </el-button>
        <el-button @click="resetSearch">重置</el-button>
      </div>
      <div class="action-buttons">
        <el-button @click="markAllAsRead">
          <el-icon><CheckCircle /></el-icon> 全部标为已读
        </el-button>
        <el-button @click="refreshData">
          <el-icon><Refresh /></el-icon> 刷新
        </el-button>
        <el-button @click="downloadData">
          <el-icon><Download /></el-icon> 导出
        </el-button>
        <el-button @click="showFilter">
          <el-icon><Filter /></el-icon> 筛选
        </el-button>
      </div>
    </div>

    <el-table
      v-loading="loading"
      :data="messageList"
      style="width: 100%;"
      border
      @row-click="openViewDialog"
    >
      <el-table-column prop="id" label="ID" width="80" align="center" />
      <el-table-column label="标题" width="200">
        <template #default="{ row }">
          <div class="message-title">
            <span :class="{ 'unread': !row.isRead }">{{ row.title }}</span>
            <el-badge v-if="!row.isRead" is-dot class="unread-dot" />
          </div>
        </template>
      </el-table-column>
      <el-table-column label="内容" width="300">
        <template #default="{ row }">
          <div class="message-content">{{ row.content }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="sender" label="发送者" width="120" />
      <el-table-column prop="sendTime" label="发送时间" width="180" align="center" :formatter="formatDate" />
      <el-table-column prop="type" label="类型" width="100" align="center">
        <template #default="{ row }">
          <el-tag
            :type="row.type === '警告' ? 'danger' : row.type === '提醒' ? 'warning' : row.type === '通知' ? 'primary' : 'success'"
          >
            {{ row.type }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="120" fixed="right" align="center">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click.stop="openViewDialog(row)">
            <el-icon><FileText /></el-icon> 查看
          </el-button>
          <el-button type="danger" size="small" @click.stop="deleteMessage(row.id)">
            <el-icon><Trash /></el-icon> 删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 查看对话框 -->
    <el-dialog v-model="viewDialogVisible" title="查看消息" width="600px">
      <div class="message-detail">
        <div class="message-header">
          <div class="message-title-detail">{{ currentMessage.title }}</div>
          <div class="message-meta">
            <span class="message-sender"><el-icon><User size="14" /></el-icon> {{ currentMessage.sender }}</span>
            <span class="message-time"><el-icon><Clock size="14" /></el-icon> {{ formatDate(currentMessage.sendTime) }}</span>
            <el-tag
              :type="currentMessage.type === '警告' ? 'danger' : currentMessage.type === '提醒' ? 'warning' : currentMessage.type === '通知' ? 'primary' : 'success'"
              size="small"
            >
              {{ currentMessage.type }}
            </el-tag>
          </div>
        </div>
        <div class="message-content-detail">{{ currentMessage.content }}</div>
      </div>
      <template #footer>
        <el-button @click="closeViewDialog">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.messages-container {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 10px;
}

.search-bar {
  display: flex;
  align-items: center;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

.message-title {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.unread {
  font-weight: bold;
}

.unread-dot {
  margin-left: 5px;
}

.message-content {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  cursor: pointer;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.message-detail {
  padding: 10px 0;
}

.message-header {
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.message-title-detail {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 10px;
}

.message-meta {
  display: flex;
  align-items: center;
  gap: 15px;
  color: #606266;
  font-size: 14px;
}

.message-content-detail {
  line-height: 1.6;
  font-size: 16px;
  white-space: pre-wrap;
}
</style>